﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using JetBrains.Annotations;

public class JsonSerializer<T>
{
    public static string SerializeToString(T obj)
    {
        byte[] temp = SerializeToBytes(obj);
        return Encoding.UTF8.GetString(temp);
    }

    [NotNull]
    public static byte[] SerializeToBytes(T obj)
    {
        using (var temp = SerializeToStream(obj))
        {
            var length = (int)temp.Length;
            var bytes = new byte[length];
            temp.Read(bytes, 0, length);
            return bytes;
        }
    }

    public static  MemoryStream SerializeToStream(T obj)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        var body = new MemoryStream();
        serializer.WriteObject(body, obj);
        body.Flush();
        body.Position = 0;
        return body;
    }
}